//
//  DataExtension.swift
//  XWHAOfflineFitting
//
//  Created by edy on 2024/7/10.
//

import Foundation

public extension Data {
    
    init(reading input: InputStream) {
        self.init()
        input.open()
        
        let bufferSize = 1024
        let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
        while input.hasBytesAvailable {
            let read = input.read(buffer, maxLength: bufferSize)
            self.append(buffer, count: read)
        }
        buffer.deallocate()
        
        input.close()
    }
    
    init(reading input: InputStream, for byteCount: Int) {
        self.init()
        input.open()

        let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: byteCount)
        let read = input.read(buffer, maxLength: byteCount)
        self.append(buffer, count: read)
        buffer.deallocate()
    }
    
    static func readAllBytes(fileAtPath: String) throws -> [UInt8] {
        if let stream: InputStream = InputStream(fileAtPath: fileAtPath) {
            return [UInt8](Data.init(reading: stream))
        }
        
        return [UInt8]()
    }
    
}
